/**
 * Created by liyun on 2015/10/27.
 */
var fs = require("fs");
var gm = require('gm');
var debug = require('debug')('routes:shop_goods');
require('date-utils');
var shop_goods = require('../models/shop_goods').shop_goods;

module.exports = function (app) {

    app.get('/goods/list', list);
    //app.get('/weixin', weixin);

    app.post('/goods/add',add);
    app.get('/goods/add',goAddPage);
    app.post('/goods/edit',edit);
    app.post('/goods/del',del);
    app.get('/goods/edit',goEditPage);
    app.post('/goods/uploadsThumb',uploadsThumb);


};


function uploadsThumb(req,res){
    console.log('upload');
    var filepath = req.files.fileList.path;
    var name = req.files.fileList.name;
    fs.rename(filepath,'public/images/goods/'+name,function(err){
        debug(err);
        if(err){
            res.send(500);
        }else{
            res.send('/images/goods/'+name);
        }

    });
};

function list(req,res){
    var pagenum =1;
    if(req.query.page){
        pagenum = req.query.page;
    }
    getGoods(pagenum,req,res);

};

function goAddPage(req,res){
    var rid = 0;
    if(req.query.id){
        rid = req.query.id;
    }
    res.render('shop/goods_create',{rid:rid});
};

function goEditPage(req,res){
    var id = req.query.id;
    new shop_goods().findOne(id,function(result){
        res.render('shop/goods_edit',{goods:result[0]});
    });

};

function add(req,res){
    var goods = req.body;
    if(goods.rid=='null'){
        delete goods.rid;
    }

    new shop_goods().add(goods,function(result){
        getGoods(1,req,res);
    });
};

function edit(req,res){
    var goods = req.body;
    if(goods.thumb!=goods.oldthumb){
        var urls = goods.oldthumb.split(',');
        for(var i=0;i<urls.length;i++){
            var unlinkPath='public'+urls[i];
            if(fs.exists(unlinkPath))
                fs.unlinkSync();
        }

    }
    new shop_goods().edit(goods,function(result){
        getGoods(1,req,res);
    });
};

function del(req,res){
    var id = req.body.id;
    new shop_goods().del(id,function(result){
        res.send(result);
    });
};

function getGoods(pagenum,req,res){
    var page = ['shop_goods.createtime','desc',(Number(pagenum)-1)*10,10];

    new shop_goods().list(page,function(data){
        debug(data);
        if(req.query.page){
            res.send(data);
        }else{
            res.render('shop/goods_list',{data:data});
        }
        //
    });
}